package com.huatai.common.error;

/**
 * @program: ht-system
 * @description: 全局异常捕获
 * @author: songxiude
 * @create: 2023-01-31 16:50
 **/

import javax.servlet.Servlet;

import com.huatai.common.api.R;
import com.huatai.common.api.ResultCode;
import com.huatai.common.error.exception.SecureException;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.Func;
import com.huatai.common.util.UrlUtil;
import com.huatai.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.DispatcherServlet;

@Order
@Configuration
@ConditionalOnWebApplication(
        type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@RestControllerAdvice
public class HtRestExceptionTranslator {
    private static final Logger log = LoggerFactory.getLogger(HtRestExceptionTranslator.class);

    public HtRestExceptionTranslator() {
    }

    @ExceptionHandler({ServiceException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleError(ServiceException e) {
        log.error("业务异常", e);
        System.out.println("asadada");
        return R.fail(e.getResultCode(), e.getMessage());
    }

    @ExceptionHandler({SecureException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R handleError(SecureException e) {
        log.error("认证异常", e);
        return R.fail(e.getResultCode(), e.getMessage());
    }

    @ExceptionHandler({Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleError(Throwable e) {
        log.error("服务器异常", e);
        ErrorLogPublisher.publishEvent(e, UrlUtil.getPath(WebUtil.getRequest().getRequestURI()));
        return R.fail(ResultCode.INTERNAL_SERVER_ERROR, Func.isEmpty(e.getMessage()) ? ResultCode.INTERNAL_SERVER_ERROR.getMessage() : e.getMessage());
    }
}

